#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 

#include "Package.h"
#include "UDPReceiver.h"
#include "../logger/Logger.h"

Info receiveCoords() {
	// 1. Construct the local socket address
	sockaddr_in si_me, src_addr;
	int s;
	int port = 3200;
	int broadcast = 1;

	// 2. Create the socket
	s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	setsockopt(s, SOL_SOCKET, SO_BROADCAST,
		    &broadcast, sizeof broadcast);

	memset(&si_me, 0, sizeof(si_me));
	si_me.sin_family = AF_INET;
	si_me.sin_port = htons(port);
	si_me.sin_addr.s_addr = INADDR_ANY;

	// 3. Bind the local address to the socket
	bind(s, (sockaddr *)&si_me, sizeof(sockaddr));

	// 4. Receive the data through the socket
	Logger::getInstance().log("UDPReceiver::receiveCoords : UDP recvfrom socket");
	
	Udp_package pack;
	socklen_t src_addr_len = sizeof(src_addr);
	recvfrom(s, &pack, sizeof(pack)-1, 0, (sockaddr *)&src_addr, &src_addr_len);

	// get the coordinates for groep_b
	Info coords = pack.info_b;

	close(s); // close the socket TODO: make a class and move this to destructor

	return coords;
}
